#!/bin/bash

(
    set -e 
    cd "$(dirname "$0")"
  
    targetBin="file_server"
    buildDir="/tmp/goBuild_for_${targetBin}/"
    

    builderImage="golang:1.15-buster"


    builderScript="build.sh"
    if [ ! -e "$buildDir" ]; then
      mkdir -p "$buildDir"
    fi

    echo "[I] docker build dir == $buildDir"

    cat >"$buildDir/$builderScript" <<EOF
#!/bin/bash

# RUN go build -o /${targetBin} /src/*.go

echo "[I] build for arm v7"
GOOS=linux GOARCH=arm GOARM=7 go build -o /build/${targetBin}_arm7   /src/*.go
echo "[I] build for arm64"
GOOS=linux GOARCH=arm64 go build -o /build/${targetBin}_arm64        /src/*.go
echo "[I] build for amd64"
GOOS=linux GOARCH=amd64 go build -o /build/${targetBin}_amd64        /src/*.go

echo "date :: list files :: "
ls -alF /build/

EOF


    containerName="builder_for_${targetBin}"
    sudo docker run --rm \
      --name "$containerName" \
      -v "$(pwd)/src":/src:ro \
      -v "${buildDir}":"/build" \
      -e GO111MODULE="on" \
      -e GOPROXY="https://goproxy.cn,direct" \
      -w "/src" \
      "$builderImage" \
      bash "/build/$builderScript"




##############################

    image="inthbl/${targetBin}"

    #
    sudo docker run --rm --privileged multiarch/qemu-user-static --reset -p yes
    sudo docker buildx create --name multiarch-builder --driver docker-container --use || true
    sudo docker buildx inspect --bootstrap

    
    # /build/statics
    cp -r ./src/statics ./src/Dockerfile "$buildDir/"

    cat >"$buildDir/copy.sh" <<EOF
#!/bin/bash

copyFunc(){
  if [ -z "\$2" ];then
    return
  fi

  if [ "x\$TARGETPLATFORM" == "x\$1" ];then
    cp "\$2" "/build/${targetBin}"
  fi
}


copyFunc linux/amd64  /build/${targetBin}_amd64
copyFunc linux/arm64  /build/${targetBin}_arm64
copyFunc linux/arm/v7 /build/${targetBin}_arm7

if [ ! -e "/build/${targetBin}" ];then
  echo "[Err] cant find binary file"
  exit 1
else
  ls -l "/build/${targetBin}"
fi

EOF

################

    sudo docker buildx build --push --platform=linux/amd64,linux/arm64,linux/arm/v7 \
      -f "$buildDir/Dockerfile" -t $image \
      "$buildDir"
    ## arg  --push : push to hub.  
    ##      sudo docker login

)

